package com.gamemost.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.gamemost.dao.BookDatasource;
import com.gamemost.layout.LayoutViewReadBook;
import com.gamemost.libepub.ItemRef;
import com.gamemost.managers.ResourcesManager;
import com.gamemost.templestay.Config;

public class DownloadedBook extends BookService {
	private ArrayList<Bookmark> bmarkArray = new ArrayList<Bookmark>();
	private boolean loadBookmark;
	
	public boolean isLoadBookmark() {
		return loadBookmark;
	}

	public void setLoadBookmark(boolean loadBookmark) {
		this.loadBookmark = loadBookmark;
	}
	
	public void addBookmarkReflow(Bookmark bm) {
		addToBookmarkMap(bm);
	}

	public String getListBookmarkOfChapter(int cIndex) {
		String bm = "";
		if (bookmarkMap.containsKey(cIndex)) {
			ArrayList<Bookmark> list = bookmarkMap.get(cIndex);
			for (int i = 0; i < list.size(); i++) {
				String tmpBm = list.get(i).getBookmark();
				if (i != list.size() - 1) {
					bm += tmpBm + "afd_divide";
				} else {
					bm += tmpBm;
				}
			}
		}
		return bm;
	}
	public void delBookmarkReflow (int cIndex, int index) {
		System.out.println("updateBookmark del "+index+","+cIndex);
		ArrayList<Bookmark> list = bookmarkMap.get(cIndex);		
		System.out.println("remove delBookmark before "+list.size());
		Bookmark bm = list.remove(index);
		if(list.size() == 0) bookmarkMap.remove(cIndex);

		if (bmarkArray.remove(bm)) System.out.println("reflowBookmark delete also");
		BookDatasource.getInstance(ResourcesManager.ac.getBaseContext()).updateBookmarkReflow(this);
	}
	public String getStringBMReflow() {
		String bm = "";
//		System.out.println("getStringBMReflow:" + bmarkArray.size());
//		for (int i = 0; i < bmarkArray.size(); i++) {
//			if (i != bmarkArray.size() - 1) {
//				bm += bmarkArray.get(i).getBookmark() + "afd_divide";
//			} else {
//				bm += bmarkArray.get(i).getBookmark();
//			}
//		}

		 Set<Integer> cIndexSet = bookmarkMap.keySet();
		 
		 Iterator<Integer> cIndexIter = cIndexSet.iterator();
		 
		 while (cIndexIter.hasNext()) {
		 if (!"".equals(bm)) {
			 bm += "afd_divide";
		 }
		 Integer cIndex = cIndexIter.next();
		 ArrayList<Bookmark> list = bookmarkMap.get(cIndex);
		 System.out.println("getStringBMReflow chapter "+cIndex+", listsize "+list.size());

		 for (int i = 0; i < list.size(); i++) {
		 if (i != list.size() - 1) {
		 bm += list.get(i).getBookmark() + "afd_divide";
		 } else {
		 bm += list.get(i).getBookmark();
		 }
		 }
		 }
		return bm;
	}

	public void delBookmarkReflow(int i) {
		bmarkArray.remove(i);
	}

	public ArrayList<Bookmark> getBmarkArray() {
		return bmarkArray;
	}

	public void setBmarkArray(ArrayList<Bookmark> bmarkArray) {
		this.bmarkArray = bmarkArray;
	}

	private String filename;
	public HashMap<Integer, ArrayList<Bookmark>> bookmarkMap = new HashMap<Integer, ArrayList<Bookmark>>();

	public ArrayList<String> getListString() {
		ArrayList<String> list = new ArrayList<String>();
		Iterator<String> iter = bookmark.keySet().iterator();
		while (iter.hasNext()) {
			String name = iter.next();
			list.add(name);
		}
		return list;
	}

	public boolean haveBookmark() {
		System.out.println(bookmark.size() + " bookmarkString "
				+ bookmarkString);
		if (bookmark.size() > 0)
			return true;
		else
			return false;
	}

	HashMap<String, String> bookmark = new HashMap<String, String>();
	String bookmarkString = "";

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public HashMap<String, String> getBookmark() {
		return bookmark;
	}

	public DownloadedBook() {

	}

	public DownloadedBook(String id, String file_name, String image,
			String bookmark, int typeBook) {
		this.filename = file_name;
		this.id = id;
		this.image = image;
		this.typeBook = typeBook;
		setBookmark(bookmark);
		bookmarkString = bookmark;
		System.out.println(typeBook + " bookmarklll " + bookmarkString);
	}

	public void addToBookmarkMap(Bookmark bm) {
		int cIndex = bm.getcIndex();
		if (bookmarkMap.containsValue(bm)) return;
		if (!bookmarkMap.containsKey(cIndex)) {
			ArrayList<Bookmark> list = new ArrayList<Bookmark>();
			list.add(bm);
			bookmarkMap.put(cIndex, list);
		} else {
			bookmarkMap.get(cIndex).add(bm);
		}
		if(!bmarkArray.contains(bm)) bmarkArray.add(bm);
	}

	// public int findPercentFromBookmark(String idref, int unitPercent,
	// int curPercent) {
	// if (bookmarkMap.containsKey(idref)) {
	// ArrayList<Integer> list = bookmarkMap.get(idref);
	// int delta = 11000, tmp, index = -1;
	// for (int i = 0; i < list.size(); i++) {
	// tmp = list.get(i) - curPercent;
	// System.out.println("checkBookmarkPage tmp"
	// + (float) unitPercent / 2);
	// if (tmp < 0)
	// tmp = tmp * (-1);
	// if (tmp >= ((float) unitPercent / 2))
	// continue;
	// if (delta > tmp) {
	// delta = tmp;
	// index = i;
	// }
	// }
	// if (index != -1)
	// return list.get(index);
	// return -1;
	// }
	// return -1;
	// }

	public void setBookmark(String bookmark) {
		if (typeBook == Config.FIX_LAYOUT) {
			System.out.println("aaaaaabbbbbbbccccccc config");
			if (bookmark != null && !" ".equals(bookmark)) {
				String[] listElm;
				if (bookmark.contains(",")) {
					listElm = bookmark.split(",");
					for (int i = 0; i < listElm.length; i++) {
						// format page&name,page&name
						String[] elm = listElm[i].split("&");
						System.out.println("elm " + listElm[i] + " elm0 "
								+ elm[0] + ", elm1 " + elm[1]);
						if (elm.length > 1) {
							this.bookmark.put(elm[1],
									elm[0].substring(1, elm[0].length() - 1));
							// if (elm[0].contains("#")) {
							// addToBookmarkMap(elm[0].substring(1,
							// elm[0].length() - 1));
							// }
						}
					}
				} else if (bookmark.contains("&")) {

					String[] elm = bookmark.split("&");
					if (elm.length > 1) {
						this.bookmark.put(elm[1],
								elm[0].substring(1, elm[0].length() - 1));
						System.out.println("put bookmark " + elm[1] + " va "
								+ elm[0]);

					}
				}
			}
		} else {
			if (bookmark != null && !"null".equals(bookmark)
					&& !"".equals(bookmark)) {
				System.out.println("aaaaaaaaaaaaaaa bookmark "+bookmark);

				String[] tmpArr = bookmark.split("afd_divide");
				for (int i = 0; i < tmpArr.length; i++) {
					String bmData = tmpArr[i];
					System.out.println("aaaaaaaaaaaaaaa bookmark i "+i+":::"+bmData);

					String[] dataArr = bmData.split("afd_item");
					Bookmark bm = new Bookmark(Integer.parseInt(dataArr[0]),
							Integer.parseInt(dataArr[1]),
							Integer.parseInt(dataArr[2]), dataArr[3]);
					bm.setBookmark(bmData);
					// bmarkArray.add(bm);
					// addToBookmarkMap(bm);

					addBookmarkReflow(bm);
				}
				tmpArr = null;
				System.gc();
			}
		}
	}

	public void addBookmark(int page, boolean isFixLayout) {
		String name = "";
		String idref = LayoutViewReadBook.tableContent.getItemRef(page)
				.getIdref();
		String id = "";
		// if (!isFixLayout) {
		// LayoutViewReadBook.getInstance().getHtml5WebView().loadUrl("javascript:window.Android.addBookmark()");
		// } else {
		name = generateImage(page, 0);
		System.out.println("bookmark isFixLayout");
		id = "(" + idref + ")";
		// }
		String bookmark = id + "&" + name;
		System.out.println("bookmark is " + id);
		if (bookmarkString.contains("&"))
			bookmark = "," + bookmark;
		bookmarkString += bookmark;
		System.out.println("bookmark add " + bookmark);
		this.bookmark.put(name, id.substring(1, id.length() - 1));
	}

	public void delBookmark(int page) {
		System.out.println("delbmbm " + percentPageBookmark);
		bookmark.remove(generateImage(page, 0));
	}

	public String getBookmarkString() {
		Set<String> namePage = bookmark.keySet();
		Iterator<String> iter = namePage.iterator();
		String bookmarkString = "";
		while (iter.hasNext()) {
			String name = iter.next();
			String page = bookmark.get(name);
			bookmarkString += "(" + page + ")" + "&" + name + ",";
		}
		if (bookmarkString.length() > 1)
			bookmarkString = bookmarkString.substring(0,
					bookmarkString.length() - 1);
		return bookmarkString;
	}

	public String generateImage(int page, int percent) {
		String name = "";
		name = getId() + "_page" + page + "_" + percent + ".jpg";
		return name;
	}

	int percentPageBookmark = -1;

	public boolean checkBookmarkPage(int page, boolean isFixLayout) {
		ItemRef aItem = LayoutViewReadBook.tableContent.getItemRef(page);
		String val = "";
		if (aItem != null) {
			val = aItem.getIdref();
			// if (isFixLayout) {
			// String idref =
			// LayoutViewReadBook.tableContent.getItemRef(page).getIdref();
			// int unitPercent = (int) (10000D /
			// LayoutViewReadBook.getItemPage(LayoutViewReadBook.currentPage).getNumPages());
			// percentPageBookmark = findPercentFromBookmark(idref,
			// unitPercent,LayoutViewReadBook.current_percent);
			// val += "#"+percentPageBookmark;
			// System.out.println(LayoutViewReadBook.getInstance().fromBookmark+" loadSinglePage "+percentPageBookmark+"===="+unitPercent+"====="+LayoutViewReadBook.current_percent);
			// return
			// LayoutViewReadBook.getInstance().getHtml5WebView().loadUrl("javascript:window.Android.checkBookmark(checkBookmark())");
			// }
			Iterator<String> iter = bookmark.keySet().iterator();
			while (iter.hasNext()) {
				String name = iter.next();
				if (bookmark.get(name).contains(val))
					return true;
			}
		}
		return false;
	}
}
